package com.htgd.gardenexpo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConTheaterPlanMapper;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConTheaterPlan;
import com.htgd.gardenexpo.entity.GeConTheaterPlanReserve;
import com.htgd.gardenexpo.dao.GeConTheaterPlanReserveMapper;
import com.htgd.gardenexpo.service.IGeConTheaterPlanReserveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.vo.MyTheaterRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 剧场预约 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-17
 */
@Service
public class GeConTheaterPlanReserveServiceImpl extends ServiceImpl<GeConTheaterPlanReserveMapper, GeConTheaterPlanReserve> implements IGeConTheaterPlanReserveService {

    @Autowired
    private GeConTheaterPlanReserveMapper geConTheaterPlanReserveMapper;

    @Autowired
    private GeConTheaterPlanMapper geConTheaterPlanMapper;

    @Override
    public CommonResult add(GeConTheaterPlanReserve geConTheaterPlanReserve, String openId) {
        //判断人数限制
        if(geConTheaterPlanReserve.getNum()>3){
            return CommonResult.error("最多可预约3人");
        }
        //判断是否超了
        Long count = lambdaQuery().eq(GeConTheaterPlanReserve::getPlanId, geConTheaterPlanReserve.getPlanId()).count();
        if(count+geConTheaterPlanReserve.getNum()>50){
            return CommonResult.error("预约人数超限");
        }
        //判断是否重复预约
        boolean exists = lambdaQuery().eq(GeConTheaterPlanReserve::getPlanId, geConTheaterPlanReserve.getPlanId())
                .eq(GeConTheaterPlanReserve::getOpenId, openId).exists();
        if(exists){
            return CommonResult.error("此计划已经预约，无法重复预约");
        }
        //判断是否超过预约时间
        GeConTheaterPlan geConTheaterPlan = geConTheaterPlanMapper.selectById(geConTheaterPlanReserve.getPlanId());
        if(LocalDate.now().isAfter(geConTheaterPlan.getStartTime())){
            return CommonResult.error("预约时间已过，不可预约");
        }
        //插入数据
        geConTheaterPlanReserve.setOpenId(openId);
        geConTheaterPlanReserveMapper.insert(geConTheaterPlanReserve);
        return CommonResult.success("预约成功");
    }

    @Override
    public CommonResult getMyRecord(String openId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<MyTheaterRecordVO> myTheaterRecordVOS = geConTheaterPlanReserveMapper.getMyRecord(openId);
        PageInfo<MyTheaterRecordVO> list = new PageInfo<>(myTheaterRecordVOS);
        return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
    }
}
